/**
 * Created by zhoulin on 2019/4/3.
 */
var companyId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.companyId);
var schoolId = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolId);
var schoolMap = sessionStorageUtils.getJson(storageKey.sessionStorageKey.schoolMap);

var E = window.wangEditor;
var editor = new E('#editor');

var app = new Vue({
    el: '#app',
    data: {
        permissions: ['activity:add', 'activity:update'],//本页权限数组
        selects: [],
        desc: '',
        placeId: '',
        saleId: '',
        isPush: '',
        saleTypes: [],
        list: [],
        isDisable: true,
        schoolId: schoolId,
        schoolList: schoolMap,
        salePoint: '',
    },
    //进入页面初始化方法
    created: function () {
        var that = this;
        that.getTypeList();
        that.getTagList();
        var token = sessionStorageUtils.getJson(storageKey.sessionStorageKey.token);
        if (empty(token)) {
            layer.msg("<span style='color:red'>登录超时！请重新登录！</span>", {time: 1500, icon: 5});
            setTimeout(function () {
                window.location.href = _LOGIN_PAGE;
            }, 1200);

            return;
        }
        if (!empty(aGET.id)) {
            that.getInfoById(aGET.id);
        } else {
            that.isDisable = false;
            that.setPlaces();
            that.setSales();
        }

    },
    filters: {
        numFilter(value) {
            // 截取当前数据到小数点后两位
            return parseFloat(value).toFixed(2)
        }
    },
    methods: {
        //权限控制
        permission: function (index) {
            return (_PERMISSIONS.indexOf(this.permissions[index]) != -1);
        },
        // 得到微信文章
        getWxArticle: function () {
            var that = this;
            let url = $("#contentUrl").val();
            if (url == null || url == '') {
                layer.msg("链接为空。", {time: 1500, icon: 5});
                return;
            }
            Post(that, _HOST + _API.actArt_article_getWxArticle, {url: url}, true, '')
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            var result = response.data;
                            editor.txt.html(result.content);
                            initFileUpload(result.imgUrl);
                            $("#activityImg").val(result.imgId);
                            $(".file-caption-name").text(result.imgId);
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                })
        },
        getTypeList: function () {
            var that = this;
            Get(that, _HOST + _API.actArt_activityType_getActivityClass + "?companyId=" + companyId + "&schoolId=" + schoolId)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        that.selects = response;
                    }
                });
        },
        getTagList: function () {
            var that = this;
            Get(that, _HOST + _API.common_tag_getTagsByType + "?type=1&companyId=" + companyId + "&schoolId=" + schoolId)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        initSelect(response.list);
                    }
                });
        },
        getInfoById: function (id) {
            var that = this;
            Get(that, _HOST + _API.actArt_activity_getById + "?id=" + id)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            var list = response.data;
                            var oldImgId = "";
                            for (var item in list) {
                                if (item == 'imgId') {
                                    oldImgId = list[item];
                                }
                                if (item == 'details') {
                                    editor.txt.html(list[item]);
                                }
                                if (item == 'showUrl') {
                                    initFileUpload(list[item]);
                                }
                                if (item == 'classId') {
                                    $("#Form select[name='classId']").val(list[item]);
                                }
                                if (item == 'isPush') {
                                    that.isPush = list[item];
                                    if (that.isPush == -1 || that.isPush == 1) {
                                        layer.msg("当前活动记录不可修改！", {time: 1500, icon: 5});
                                    }
                                    $("#Form select[name='isPush']").val(list[item]);
                                }
                                if (item == 'isTop') {
                                    $("#Form select[name='isTop']").val(list[item]);
                                }
                                if (item == 'describe') {
                                    that.desc = list[item];
                                }
                                if (item == 'schoolId') {
                                    $("#Form select[name='schoolId']").val(list[item]);
                                }
                                if (item == 'activityType') {
                                    $("#Form select[name='activityType']").val(list[item]);
                                }
                                // 设置地点
                                if (item == 'placeId') {
                                    that.placeId = list[item];
                                }
                                if (item == 'saleId') {
                                    that.saleId = list[item];
                                }
                                if (item == 'tags') {
                                    selectTags(list[item]);
                                    continue;
                                }
                                if (item == 'applyEndTime' || item == 'beginTime' || item == 'signIn' || item == 'endTime') {
                                    $("#Form input[name='" + item + "']").val(formatDateTime(list[item]));
                                } else {
                                    $("#Form input[name='" + item + "']").val(list[item]);
                                }
                            }
                            $("#Form input[name='oldImgId']").val(oldImgId);
                            $("#Form").data('bootstrapValidator').destroy();
                            $('#Form').data('bootstrapValidator', null);
                            Validator();
                            that.setPlaces();
                            that.setSales();
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                        // 设置比例
                        var salePoint = response.salePoint;
                        if (!empty(salePoint)) {
                            that.salePoint = salePoint;
                        }
                        // 设置票价
                        var sales = response.salesRelations;
                        if (!empty(sales)) {
                            that.initSale(sales);
                        }
                    }
                })
        },
        // 添加
        add: function () {
            var that = this;
            $("#details").val(editor.txt.html());
            var param = {};
            var flag = true;
            $("#Form").find('input,textarea,select').each(function () {
                if ($(this).attr('name') == 'latLng') {
                    if (empty($(this).val())) {
                        flag = false;
                        layer.msg('经纬度不能为空！', {time: 1500, icon: 5});
                    }
                }
                if ($(this).attr('name') == 'applyEndTime') {
                    if (empty($(this).val())) {
                        flag = false;
                        layer.msg('报名截止时间不能为空！', {time: 1500, icon: 5});
                    }
                }
                if ($(this).attr('name') == 'beginTime') {
                    if (empty($(this).val())) {
                        flag = false;
                        layer.msg('活动开始时间不能为空！', {time: 1500, icon: 5});
                    }
                }
                if ($(this).attr('name') == 'endTime') {
                    if (empty($(this).val())) {
                        flag = false;
                        layer.msg('活动结束时间不能为空！', {time: 1500, icon: 5});
                    }
                }
                if ($(this).attr('name') == 'signIn') {
                    if (empty($(this).val())) {
                        flag = false;
                        layer.msg('活动签到时间不能为空！', {time: 1500, icon: 5});
                    }
                }
                param[$(this).attr('name')] = $(this).val();
            });
            if (!flag) {
                return;
            }
            // 得到标签
            var tagArr = $("#tags").val();
            var ids = "";
            if (!empty(tagArr)) {
                for (let i = 0; i < tagArr.length; i++) {
                    ids += tagArr[i];
                    if ((i + 1) != tagArr.length) {
                        ids += ",";
                    }
                }
            }
            param['tags'] = ids;
            param['companyId'] = companyId;
            // 设置票价
            var bl = that.getSaleMap();
            if (bl == 1) {
                layer.msg("票价设置应遵守规则：原价>=票价>=预付款", {time: 1500, icon: 5});
                return;
            } else if (bl == 2) {
                layer.msg("若一类为全款，其他类型都应为全款。", {time: 1500, icon: 5});
                return;
            } else if (bl == 3) {
                layer.msg("售票类型配置不能有空值", {time: 1500, icon: 5});
                return;
            }
            param['priceJsonString'] = JSON.stringify(that.list);
            // console.log(param)
            var info = "是否确定保存？";
            if (param.isPush == 1) {
                info = "状态为发布或者取消发布的记录无法再次修改，是否确定保存？";
            }
            var confirm = layer.confirm(info, {
                btn: ['确定', '取消'], //按钮
                shadeClose: false,
            }, function () {
                Post(that, _HOST + _API.actArt_activity_add, param, true, that.permissions[0])
                    .then(function (response) {
                        // 响应成功回调
                        console.log(response);
                        layer.close(confirm);
                        if (response) {
                            if (response.success) {
                                layer.msg(response.msg, {time: 1500, icon: 1});
                                setTimeout(function () {
                                    window.parent.location.reload(); //刷新父页面
                                    layer.closeAll();
                                }, 1500)
                            } else {
                                layer.msg(response.msg, {time: 1500, icon: 5});
                            }
                        }
                        $("#Form").data('bootstrapValidator').destroy();
                        $('#Form').data('bootstrapValidator', null);
                        Validator();
                    })
            });

        },
        // 修改
        update: function () {
            var that = this;
            $("#details").val(editor.txt.html());
            var param = {};
            var flag = true;
            $("#Form").find('input,textarea,select').each(function () {
                if ($(this).attr('name') == 'latLng') {
                    if (empty($(this).val())) {
                        flag = false;
                        layer.msg('经纬度不能为空！', {time: 1500, icon: 5});
                    }
                }
                if ($(this).attr('name') == 'applyEndTime') {
                    if (empty($(this).val())) {
                        flag = false;
                        layer.msg('报名截止时间不能为空！', {time: 1500, icon: 5});
                    }
                }
                if ($(this).attr('name') == 'beginTime') {
                    if (empty($(this).val())) {
                        flag = false;
                        layer.msg('活动开始时间不能为空！', {time: 1500, icon: 5});
                    }
                }
                if ($(this).attr('name') == 'endTime') {
                    if (empty($(this).val())) {
                        flag = false;
                        layer.msg('活动结束时间不能为空！', {time: 1500, icon: 5});
                    }
                }
                if ($(this).attr('name') == 'signIn') {
                    if (empty($(this).val())) {
                        flag = false;
                        layer.msg('活动签到时间不能为空！', {time: 1500, icon: 5});
                    }
                }
                param[$(this).attr('name')] = $(this).val();
            });
            if (!flag) {
                return;
            }
            // 得到标签
            var tagArr = $("#tags").val();
            var ids = "";
            if (!empty(tagArr)) {
                for (let i = 0; i < tagArr.length; i++) {
                    ids += tagArr[i];
                    if ((i + 1) != tagArr.length) {
                        ids += ",";
                    }
                }
            }
            param['tags'] = ids;
            param['companyId'] = companyId;
            // 设置票价
            var bl = that.getSaleMap();
            if (bl==1) {
                layer.msg("票价设置应遵守规则：原价>=票价>=预付款", {time: 1500, icon: 5});
                return;
            } else if (bl == 2) {
                layer.msg("若一类为全款，其他类型都应为全款。", {time: 1500, icon: 5});
                return;
            } else if (bl == 3) {
                layer.msg("售票类型配置不能有空值", {time: 1500, icon: 5});
                return;
            }
            param['priceJsonString'] = JSON.stringify(that.list);
            // console.log(param)
            var info = "是否确定保存？";
            if (param.isPush == 1) {
                info = "状态为发布或者取消发布的记录无法再次修改，是否确定保存？";
            }
            var confirm = layer.confirm(info, {
                btn: ['确定', '取消'], //按钮
                shadeClose: false,
            }, function () {
                Post(that, _HOST + _API.actArt_activity_update, param, true, that.permissions[1])
                    .then(function (response) {
                        // 响应成功回调
                        console.log(response);
                        layer.close(confirm);
                        if (response) {
                            if (response.success) {
                                layer.msg(response.msg, {time: 1500, icon: 1});
                                setTimeout(function () {
                                    window.parent.location.reload(); //刷新父页面
                                    layer.closeAll();
                                }, 1500)
                            } else {
                                layer.msg(response.msg, {time: 1500, icon: 5});
                            }
                        }
                        $("#Form").data('bootstrapValidator').destroy();
                        $('#Form').data('bootstrapValidator', null);
                        Validator();
                    })
            });

        },
        changePlace: function () {
            var that = this;
            var address = $("#place").val();
            var indexs = layer.open({
                type: 2,
                title: "选择地址",
                content: "address.html?address="+address,
                fix: true,
                shadeClose: true,
                shade: false,
                area: ['60%', '95%'],
                maxmin: true, //开启最大化最小化按钮
                end:function(index){
                    var info = sessionStorageUtils.getJson(storageKey.sessionStorageKey.activityAddress);
                    console.log(info);
                    if (!empty(info)) {
                        $("#latLngMsg").css("display", "none");
                        $("input[name='latLng']").val(info.location.lat + ',' + info.location.lng);
                        $("input[name='address']").val(info.address);
                        $("input[name='province']").val(info.addressComponents.province);
                        $("input[name='city']").val(info.addressComponents.city);
                        $("input[name='street']").val(info.addressComponents.street);
                    } else {
                        $("#latLngMsg").css("display", "inline-block")
                    }
                }
            });
        },
        //查询设置地点
        setPlaces: function () {
            var that = this;
            Get(that, _HOST + _API.actArt_activityPlace_getPlaces+"?companyId="+companyId)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            var list = response.list;
                            var domOption = "";
                            for (var item in list) {
                                domOption += "<option value='" + list[item].id + "'>" + list[item].name + "</option>";
                            }
                            $("#placeId").html("<option value=''>---不限制场地---</option>");
                            $("#placeId").append(domOption);
                            $("#Form select[name='placeId']").val(that.placeId);
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                })
        },
        // 设置售票类型
        setSales: function () {
            var that = this;
            Get(that, _HOST + _API.actArt_activitySales_getParents+"?companyId="+companyId)
                .then(function (response) {
                    // 响应成功回调
                    console.log(response);
                    if (response) {
                        if (response.success) {
                            var list = response.list;
                            var domOption = "";
                            for (var item in list) {
                                domOption += "<option value='" + list[item].id + "'>" + list[item].name + "</option>";
                            }
                            // $("#saleId").html("<option value=''>---无收费---</option>");
                            $("#saleId").html(domOption);
                            $("#Form select[name='saleId']").val(that.saleId);
                        } else {
                            layer.msg(response.msg, {time: 1500, icon: 5});
                        }
                    }
                })
        },
        // 改变sale选项
        selectSale: function () {
            var that = this;
            var saleId = $("#Form select[name='saleId']").val();
            that.saleTypes = [];
            if (!empty(saleId)) {
                Get(that, _HOST + _API.actArt_activitySales_getchildren + "?parenId=" + saleId)
                    .then(function (response) {
                        // 响应成功回调
                        console.log(response);
                        if (response) {
                            if (response.success) {
                                var list = response.list;
                                for (let i = 0; i < list.length; i++) {
                                    if (empty(list[i].oldPrice)) {
                                        list[i].oldPrice = 0;
                                    }
                                    if (empty(list[i].price)) {
                                        list[i].price = 0;
                                    }
                                    if (empty(list[i].prePrice)) {
                                        if (empty(list[i].price)) {
                                            list[i].prePrice = 0;
                                        } else {
                                            list[i].prePrice = list[i].price;
                                        }
                                    }
                                    if (empty(list[i].allAmount)) {
                                        list[i].allAmount = 0;
                                    }
                                }
                                that.saleTypes = list;
                            } else {
                                layer.msg(response.msg, {time: 1500, icon: 5});
                            }
                        }
                    })
            }
        },
        // 得到map string
        getSaleMap: function () {
            var that = this;
            that.list = [];
            var flg = 0;
            var isAll = [];
            $('.ticket-price').each(function (index, domEle) {
                if (!empty($(domEle).val())) {
                    var obj = new Object();
                    obj.saleId = $(domEle).data().typeid;
                    obj.saleName = $(domEle).data().typename;
                    obj.price = parseFloat($(domEle).val());
                    obj.sort = 100 - index;
                    obj.allAmount = $('.ticket-amount').eq(index).val();
                    obj.nowAmount = $('.ticket-amount').eq(index).val();
                    obj.oldPrice = $('.ticket-oldPrice').eq(index).val();
                    obj.prePrice = $('.ticket-prePrice').eq(index).val();
                    obj.salePoint = that.salePoint;
                    that.list.push(obj);
                    if (empty(obj.allAmount)||empty(obj.price)||empty(obj.prePrice)) {
                        flg = 3;
                    }
                    if (obj.price == obj.prePrice) {
                        isAll.push(true);
                    } else {
                        isAll.push(false);
                    }
                    if (flg == 0) {
                        if (obj.oldPrice < obj.price || obj.price < obj.prePrice) {
                            flg = 1;
                        }
                    }
                }
            });
            if (isAll.length > 0) {
                if (!isAll.every(x => x == true)&&!isAll.every(x => x == false)) {
                    flg = 2;
                }
            }
            console.log(JSON.stringify(that.list));
            return flg;
        },
        // 初始化票价
        initSale: function (sales) {
            var that = this;
            for (let i = 0; i < sales.length; i++) {
                var obj = new Object();
                obj.id = sales[i].saleId;
                obj.name = sales[i].saleName;
                obj.price = sales[i].price;
                obj.allAmount = sales[i].allAmount;
                obj.oldPrice = sales[i].oldPrice;
                obj.prePrice = sales[i].prePrice;
                that.saleTypes.push(obj);
            }
            console.log(JSON.stringify(that.saleTypes));
        },
        minValue(index, type) {
            var that = this;
            if (1 == type) {
                if (!ckPrice(that.saleTypes[index].price)) {
                    that.saleTypes[index].price = '';
                }
            } else if (2 == type) {
                if (!ckNum(that.saleTypes[index].allAmount)) {
                    that.saleTypes[index].allAmount = '';
                }
            } else if (3 == type) {
                if (!ckPrice(that.saleTypes[index].oldPrice)) {
                    that.saleTypes[index].oldPrice = '';
                }
            } else if (4 == type) {
                if (!ckPrice(that.saleTypes[index].prePrice)) {
                    that.saleTypes[index].prePrice = '';
                }
            }
        }
    },
});


function initFileUpload(url) {
    $("#fileUploadBtn").fileinput('destroy');
    $("#fileUploadBtn").fileinput({
        language: "zh",
        uploadUrl: _HOST + _API.common_file_ossUpload,
        ajaxSettings: {
            headers: {
                'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
                'permCoding': ''
            }
        },
        browseClass: "btn btn-success",
        browseLabel: "上传预览图片",
        browseIcon: "<i class=\"glyphicon glyphicon-picture\"></i> ",
        allowedFileExtensions: ['jpg', 'gif', 'png'],
        showUpload: false,
        dropZoneEnabled: true,
        showPreview: true,
        minFileCount: 1,
        maxFileCount: 1,
        maxFileSize:6072,
        initialPreviewAsData: true,
        initialPreview: [
            url
        ],
        initialPreviewConfig: [
            {
                caption: url,
                size: 329892,
                width: "120px",
                url: url,
                key: 1
            },
        ]
    }).on("filebatchselected", function (event, files) {
        $(this).fileinput("upload");
    }).on("fileuploaded", function (event, data, previewId, index) {
        if (data.response.status) {
            $(".file-caption-name").text(data.response.attachemId);
            $("#activityImg").val(data.response.attachemId);
        } else {
            parent.layer.msg(data.response.msg, {time: 1500, icon: 5});
        }
    });
    $(".kv-file-remove").remove();
}

$(function () {
    editor.customConfig.uploadImgServer = _HOST + _API.common_file_ossWe;
    editor.customConfig.uploadFileName = 'file';
    editor.customConfig.uploadImgHeaders = {
        'Authorization': sessionStorageUtils.getJson(storageKey.sessionStorageKey.token),
        'permCoding': '',
        'enctype': 'multipart/form-data'
    };
    editor.customConfig.zIndex = 100;
    editor.create();
    if (empty(aGET.id)) {
        initFileUpload('');
    }
});

// 初始化多选
function initSelect(datas) {
    var select = $("#tags");
    for (var i = 0; i < datas.length; i++) {
        select.append("<option value='" + datas[i].id + "'>"
            + datas[i].name + "</option>");
    }
    select.selectpicker('val', '');
    select.selectpicker('refresh');
}

// 选中tag
function selectTags(value) {
    var s = document.getElementById("tags");
    console.log(value);
    if (!empty(value)) {
        var tagsArr = value.split(",");
        $('.selectpicker').selectpicker('val', tagsArr);
    }
}

$('#Form').data('bootstrapValidator', null);
Validator();

function Validator() {
    $('#Form').bootstrapValidator({
        fields: {
            title: {
                validators: {
                    notEmpty: {
                        message: '活动标题不能为空'
                    },
                    stringLength: {
                        max: 500,
                        message: '活动标题长度最多500个字符'
                    },
                }
            },
            describe: {
                validators: {
                    notEmpty: {
                        message: '活动描述不能为空'
                    },
                    stringLength: {
                        max: 999,
                        message: '活动描述长度最多999个字符'
                    },
                }
            },
            place: {
                validators: {
                    notEmpty: {
                        message: '活动地点不能为空'
                    },
                    stringLength: {
                        max: 250,
                        message: '活动地点长度最多250个字符'
                    },
                }
            },
            /*latLng: {
                validators: {
                    notEmpty: {
                        message: '活动地点经纬度不能为空'
                    },
                }
            },*/
            classId: {
                validators: {
                    notEmpty: {
                        message: '请选择活动类别'
                    },
                }
            },
            sort: {
                validators: {
                    notEmpty: {
                        message: '排序不能为空'
                    },
                }
            },
            maleLimit: {
                validators: {
                    notEmpty: {
                        message: '活动参与人数不能为空'
                    },
                }
            },
            /*signIn: {
                validators: {
                    notEmpty: {
                        message: '签到开始时间不能为空'
                    },
                }
            }, */
            charge: {
                validators: {
                    notEmpty: {
                        message: '收费标准不能为空'
                    },
                }
            }, tel: {
                validators: {
                    notEmpty: {
                        message: '活动负责人联系方式不能为空'
                    },
                }
            }, signUpFee: {
                validators: {
                    notEmpty: {
                        message: '报名费用不能为空'
                    },
                }
            },
            /*tags: {
                validators: {
                    notEmpty: {
                        message: '请选择活动标签'
                    },
                }
            },*/
            /*beginTime: {
                validators: {
                    notEmpty: {
                        message: '请选择活动开始时间'
                    },
                }
            },
            endTime: {
                validators: {
                    notEmpty: {
                        message: '请选择活动结束时间'
                    },
                }
            }*/
        }
    }).on('success.form.bv', function (e) {
        // Prevent form submission
        e.preventDefault();
        $('#Form').bootstrapValidator('disableSubmitButtons', false);
        if (empty(aGET.id)) {
            app.add();
        } else {
            app.update();
        }
    });
}
